package cn.chitanda.weather.ui

import android.app.Application
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import cn.chitanda.weather.data.db.PlaceDataBase
import cn.chitanda.weather.data.db.PlaceRepository
import cn.chitanda.weather.data.network.NetWorkService
import cn.chitanda.weather.data.weather.Basic
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class PlaceViewModel(application: Application) : AndroidViewModel(application) {
    private val a = application
    private val dao = PlaceDataBase.getInstance(application.applicationContext).getPlaceDao()
    private val network = NetWorkService.getInstance()

    private val repository = PlaceRepository.getInstance(dao, network)
    private var _cityList = repository.getAllCity()
    val cityList: LiveData<List<Basic>>
        get() = _cityList
    private val _searchResult = MutableLiveData<List<Basic>>()
    val searchResult: LiveData<List<Basic>>
        get() = _searchResult

    fun searchCity(string: String) {
//        launch({ _searchResult.value = repository.searchCity(string) }, {
//            Toast.makeText(a.applicationContext, it.message, Toast.LENGTH_SHORT).show()
//        })
        viewModelScope.launch { _searchResult.value = repository.searchCity(string) }
    }

    fun insertCity(city: Basic) {
//        launch({ repository.addCity(city) }, {
//            Toast.makeText(a.applicationContext, it.message, Toast.LENGTH_SHORT).show()
//        })
        viewModelScope.launch { repository.addCity(city) }
    }


    private suspend fun getCityList() {
        _cityList = withContext(Dispatchers.Default) {
            repository.getAllCity()
        }
    }

    private fun launch(block: suspend () -> Unit, error: suspend (Throwable) -> Unit) =
        viewModelScope.launch {
            try {
                block()
            } catch (e: Throwable) {
                error(e)
            }
        }
}